#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
DoubanTunes.py

Created by System Administrator on 2010-08-21.
Copyright (c) 2010 kebot.me All rights reserved.
"""
import time
from Tkinter import *
import tkMessageBox
from SimpleDialog import *
from ConfigParser import ConfigParser
import os
from Client import Douban_Client , iTunes_Client
from trackrecorder import recorder
from qianqianlyric import qianqian_lyric
import string
from appscript import app,k
import re
import urllib

class UIBase(object):
	config_file = ""
	#Config Client
	config = None
	options = {}
	
	def __init__(self):
		self.config = ConfigParser()
		self.config_file = os.path.join('.','config.ini')
		self.config.read( self.config_file )
	
	def readOption(self,option,group="douban"):
		try:
			value = self.config.get(group,option)
		except Exception:
			print 'Options',option,'did not exists.'
		self.options[option]=value
		return value
		
	def saveOption(self,option,value,group="douban"):
		self.options[option]=value
		return self
		
	def saveOptionsToFile(self,group='douban'):
		for opt in self.options:
			value = self.options[opt]
			self.config.set(group,opt,value)
		try:
			self.config.write(open(self.config_file,'w'))
		except Exception:
			print "Sth happens when try write config file:",self.config_file
		#print 'save success'
		return self
		
class UIMainwindow(UIBase):
	root = None
	client = None
	history = None
	qianqian = None
	
	sets = [ [None,u'同步到豆瓣'],
			 [None,u'从豆瓣获取专辑封面'],
			 [None,u'从网上获取歌词'],
			]
	
	def __init__(self,title):
		self.qianqian = qianqian_lyric()
		
		UIBase.__init__(self)
		self.root = Tk()
		self.root.title(title)
		#设置窗口大小
		self.root.geometry('320x480')
		self.history = recorder()
		self.tunes = iTunes_Client()
		self.fresh()
	
	def fresh(self):
		apikey = self.readOption('apikey')
		apisecret = self.readOption('apisecret')
		if (not apikey) or (not apisecret):
			#print u"请在设置中填写API Key"
			dlg = SimpleDialog(self.root,text = u'请填写API KEY', buttons = ['Yes'], default = 0)
			print dlg.go()
			self.showOptions()
			return
		self.client = Douban_Client(apikey,apisecret)
		
		accesskey = self.readOption('accesskey')
		accesssecret = self.readOption('accesssecret')
		if accesskey and accesssecret:
			self.client.setAccess(accesskey,accesssecret)
			#print 'you have access'
			Button(self.root,text=u"退出登录",command=self.logout).pack(fill = X)
		else:
			self.access()
			return
		
		Button(self.root,text = u'设置' ,command = self.showOptions ).pack(fill=X)
		if not self.client.login():
			exit("Login Failed, Please check your config file.")
		self.initSets()
		Button(self.root,text = u'开始同步' ,command = self.syncToiTunes ).pack()
		#self.label = Label(self.root,text=u'请在iTunes中选中要同步的歌曲然后按同步\n',bg = 'yellow')
		#self.label = StringVar()
		#Message(self.root,textvariable=self.label).pack(fill=X)#
		self.label = Text(self.root,bg='yellow')
		self.label.pack(fill=X)
		self.echo(u'请在iTunes中选中要同步的歌曲然后按同步\n')
		
		
	def initSets(self):
		for s in self.sets:
			s[0] = IntVar()
			s[0].set(1)
			Checkbutton(self.root,variable = s[0] , text = s[1]).pack()
		#print self.sets[0][0].get()

	
	def run(self):
		self.root.mainloop()
	
	def access(self):
		request,request_secret = self.client.access()
		#print request,request_secret
		#now open a safari window
		if tkMessageBox.askyesno(u"ASK", u"请在浏览器中确认后,再点确定?"):
			self.client.access_ok(request,request_secret)
		if self.client.accesskey and self.client.accesssecret:
			self.saveOption('accesskey',self.client.accesskey)
			self.saveOption('accesssecret',self.client.accesssecret)
			self.saveOptionsToFile()
			self.fresh()
		else:
			print SimpleDialog(self.root,text = u'登录失败', buttons = ['Yes'], default = 0).go()
			#print "please exit and try again."
		pass
	def logout(self):
		self.saveOption('accesskey','')
		self.saveOption('accesssecret','')
		self.saveOptionsToFile()
		self.root.destroy()
	
	
	def showOptions(self):
		Option = UIOptions()
		Option.run()
	
	def echo(self,string):
		self.label.insert(1.0,string)
		self.label.update()
		#self.label.set(self.label.get()+string)

	def syncToiTunes(self):
		self.tunes.select()
		track = self.tunes.next()
		#threads = []
		while(track):
			message = track.name()+"-"+track.artist()+"-"+track.album()+"\n"
			self.echo(message)
			
			if self.sets[0][0].get()==1:
				self.sync2douban(track) #and get cover
			if self.sets[2][0].get()==1:
				self.getLyric(track)
				#print self.sets[2][1]
			track = self.tunes.next()
		self.echo(u"同步执行结束")

	def getLyric(self,track):
		doc = self.qianqian.getFirst(track.artist(),track.name())
		if doc:
			doc = doc+"\n[Add by Kebot.me]"
			self.echo(u'成功获取歌词...')
			return track.lyrics.set(to=doc)
		else:
			self.echo(u'获取歌词失败...')
			return False

	def getCover(self,track,url):
		if self.sets[1][0].get()!=1:
			#print "need not get cover"
			return False
		count = track.count(each=k.artwork)
		if count > 0:
			self.echo(u"专辑封面已存在,跳过")
			return
		try:
			data = urllib.urlopen(url).read()
		except Exception:
			self.echo( u'无法获得图片:'+url+'\n' )
			return False
		try:
			track.artworks[1].data_.set(data)
		except Exception:
			self.echo(u"添加专辑图片失败")
			return False
		self.echo(u'成功获取专辑图片')
		return True

	def sync2douban(self,track):
		history = self.history
		client = self.client
		artist = track.artist()
		album = track.album()
		album_rating = track.album_rating()
		if history.hasTrack(album,artist):
			return
		#print artist , album , album_rating/20

		subject = client.search( album , artist )
		
		#print subject
		#exit()
		
		if subject :
			collection = None
			for li in subject.link:
				if li.rel == 'collection':
					collection = li.href
					continue
				if li.rel == 'image':
					url = re.sub('spic', 'lpic', li.href )
					self.getCover(track,url)
					continue
#client.getCollection(subject.id.text)
# You have collect this album
			if collection :
				i_rating = album_rating/20
				d_rating = client.getRating(collection)
				if d_rating:
					d_rating = string.atoi( d_rating )
				else:
					d_rating = 0
				if i_rating  == d_rating:
					pass
				else:
					self.echo(u'同步收藏到豆瓣(原来的评分:'+str(d_rating)+u',现在的评分:'+str(i_rating)+')\n')
					#print "Now sync Collection="  +  collection + "From" , d_rating , "to" , i_rating
					#Use iTunes Rating
					feed = client.service.GetCollection(collection)
					client.service.UpdateCollection(feed,'listened',[],i_rating)

			else:
				#rating == 0 -> listening ; rating > 0 -> has listened
				#print "New Album"+track.album()
				client.addCollection(subject)
		else:
			#print "Can't find album "+album
			self.echo(u'豆瓣:找不到专辑')
			history.writeError(album,artist)

		history.writeTrack(album,artist)
		pass
		


#@todo: rewrite
class UIOptions(UIBase):
	root = None
	
	#temp of options
	temp = {
		'apikey':None,
		'apisecret':None,
	}
	#load with file
	default = {}
	
	def savaOptions(self):
		for opt in self.temp:
			value = self.temp[opt].get()
			#print value
			self.config.set('douban',opt,value)
		try:
			self.config.write(open(self.config_file, "w"))
		except Exception:
			print "Something happen in your config file.(Is it writeable)"
		#print "Save Options Success."
		self.root.destroy()
		return self

	def run(self):
		self.root.mainloop()

	def list(self,option,name=None):
		if not name:
			name=option
		tem = self.temp[option]
		self.temp[option]=StringVar()
		self.temp[option].set(tem)
		del tem
		Label(self.root,text=name).pack()
		Entry(self.root,textvariable=self.temp[option]).pack()
	
	
	def __init__(self):
		UIBase.__init__(self)
		self.readTemps()
		self.root = Toplevel()
		self.root.geometry('320x240')
		self.root.title(u'设置')
		self.list("apikey",u"豆瓣提供的APIKEY")
		self.list("apisecret",u"私钥")
		Button(self.root,text = u'OK',command = self.savaOptions).pack()
		Button(self.root,text = u'清除同步历史',command = self.clearHistory).pack()
		
	def readTemps(self):
		for opt in self.temp:
			self.temp[opt]=self.readOption(opt)
		return self
		
	def clearHistory(self):
		r = recorder()
		r.clear()
		self.root.destroy()
		return self
		
def main():
	main = UIMainwindow('DoubanTunes')
	main.run()
	
	pass

if __name__ == '__main__':
	main()